/*
 *--------------------------------------------------------------------------
 *   Battlefield - A Realtime Network Multiplayer Game
 *   =======================================================
 *   Developed by Group D02 - 2009/2010 Semester 4 - CS2103
 *     Harry Nguyen Duy Hoang <nnduyhoang@yahoo.co.uk>
 *     Kent Chng Siang Rong <fivefootway@gmail.com>
 *     Lim Yong Peng <limpeng1986@gmail.com>
 *     Loh Xiankun <u0807185@nus.edu.sg>
 *   Instructed by
 *     Dr. Damith C.Rajapakse <damith@gmail.com>
 *   =======================================================
 *   $Id: PlayerManager.java 616 2010-07-27 10:56:38Z Kent $
 *   $LastChangedDate: 2010-07-27 10:56:38 +0000 (Tue, 27 Jul 2010) $
 *   $LastChangedBy: Kent $
 *--------------------------------------------------------------------------
 */
package battlefield.manager;

import battlefield.BattlefieldException;
import battlefield.entity.Player;
import battlefield.util.IDGenerator;
import java.util.HashMap;

/**
 * 
 * @author Harry Nguyen
 */
public class PlayerManager extends HashMap<Integer, Player> {

    private IDGenerator idGenerator;

    /**
     * Construct a PlayerManager object.
     * The responsibilities is to keep track of and manage all Player Object that connects to the server
     */
    public PlayerManager() {
        idGenerator = new IDGenerator();
    }

    /**
     * Returns a player object using the playerId. This playerId is suppose to
     * be make available on the client side.
     * 
     * @param playerId
     * @return Player object
     * @see Player
     * @throws BattlefieldException
     */
    public Player get(int playerId) throws BattlefieldException {
        if (super.get(playerId) == null) {
            throw new BattlefieldException("Player not found.");
        }

        return super.get(playerId);
    }

    /**
     * Returns a Player object after the client registered with the server
     * @return Player object
     */
    public Player registerPlayer() {
        Player player = new Player(idGenerator.next());
        put(player.getId(), player);
        return player;
    }

        /**
     *
     * @param player
     * @return
     * @throws BattlefieldException
     */
    public boolean isAlive(Player player) throws BattlefieldException {
        updateUnitCount(player);
        return player.isAlive();
    }

    /**
     *
     * @param player
     * @return
     * @throws BattlefieldException
     */
    public Player updateUnitCount(Player player) throws BattlefieldException {
        int aliveCounter = 0, destroyedCounter = 0;
        for (int i = 0; i < player.getMap().getUnits().size(); i++) {
            if (player.getMap().getUnits().get(i).isDestroyed()) {
                destroyedCounter++;
            } else {
                aliveCounter++;
            }
        }
        player.setUnitsAlive(aliveCounter);
        player.setUnitsDestroyed(destroyedCounter);
        return player;
    }
}
